# Implement atoi to convert a string to an integer.

# Hint: Carefully consider all possible input cases.
# If you want a challenge, please do not see below and ask yourself what are the possible input cases.

# Notes: It is intended for this problem to be specified vaguely (ie, no given input specs).
# You are responsible to gather all the input requirements up front.

#59 ms
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """

        result = 0 #结果
        hasSign = False #是否已经存在符号
        isNag = False #是否为负数
        hasNum = False #是否已经转译过数字

        for char in str:
            asc = ord(char) #获取字符ASCII码

            #如果尚未开始转译数字并且符号为空格则忽略空格
            if asc == 32 and (not hasNum):
                continue

            #如果已经存在符号并且当前字符为正负号则转译结束
            if (asc == 43 or asc == 45) and hasSign:
                break

            if asc == 43: #如果是正号
                hasSign = True #已经存在符号
                hasNum = True #已经开始转译
            elif asc == 45: #如果是负号
                hasSign = True
                hasNum = True
                isNag = True #负数
            elif asc < 48 or asc > 57: #如果不是数字则转译结束
                break

            #如果结果不为零则添加一个最低位
            if result != 0:
                result = result * 10

            num = 0 #转译的数字
            for numAsc in range(48, 58):
                if numAsc == asc: #根据字符ASCII码找到对应数字
                    result += num #结果加上数字
                    hasNum = True 
                    break

                num += 1

        #负数添加负号
        if isNag:
            result = -result

        #溢出处理
        if result > (2 ** 31) - 1:
            result = (2 ** 31) - 1
        elif result <  - (2 ** 31):
            result = - (2 ** 31)

        return result



#test
solution = Solution()
result = solution.myAtoi("+00131204")

print("\n", "/////////////////////////////////////////////////")
print("\n", result)
print("\n", "/////////////////////////////////////////////////", "\n")